const { spawn } = require('child_process');
const chokidar = require('chokidar')
const { resolve } = require('path')
const env = {
    BASE_URL: 'http://127.0.0.1:7005/api',
    PORT: '10023',
    ROOT: ''
}
Object.assign(process.env, env)
function runtime(src, log) {
    let child = null
    let timer = null
    function run() {
        if (timer !== null) {
            return ;
        }
        timer = setTimeout(() => {
            clearTimeout(timer)
            timer = null;
        }, 30)
        if (child) {
            child.kill()
        }
        child = spawn('node', [resolve(src)], {
            env: process.env,
        })
        child.stdout.on('data', function (buffer) {
            console.log(`-------------------${log} success -------------------`);
            console.log(buffer.toString('utf-8'))
        })
        child.stderr.on('data', err => {
            console.log(`-------------------${log} fail -------------------`);
            console.log(err.toString('utf-8'))
        })
    }
    run()
    return run
}

const frontRuntime = runtime('src/index.js', 'front')

const watcher = chokidar.watch(resolve('src'), {
    ignored: /assets/, // ignore dotfiles
    ignoreInitial: true,
    persistent: true
});
watcher.on('all', (event, path) => {
    console.clear()
    console.log('update', event)
    frontRuntime()
});